package com.queue.rabbitmq.mapper;

import com.queue.rabbitmq.entity.User;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitmqMapper {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendWork() {
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend("queue_work", "测试work模型：" + i);
        }
    }

    public void sendPublish() {
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend("exchange_fanout", "", "测试发布订阅模型：" + i);
        }
    }

    public void sendTopic() {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                rabbitTemplate.convertAndSend("exchange_topic", "topic.km.topic", "测试发布订阅topic模型：" + i);
            } else {
                rabbitTemplate.convertAndSend("exchange_topic", "topic.km", "测试发布订阅topic模型：" + i);
            }
        }
    }

    /**
     * 确认机制发送回调
     */
    private final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
        if (ack) {
            System.out.println("confirm 消息发送成功。。。" + correlationData.getId());
        } else {
            System.out.println("confirm 消息发送失败。。。" + correlationData.getId() + ",cause:" + cause);
        }
    };

    public void sendConfirm() {
        //new CorrelationData(""+System.currentTimeMillis()) 发送回调参数
        rabbitTemplate.convertAndSend("queue_confirm", new User(1, "km", "km123"), new CorrelationData("" + System.currentTimeMillis()));
        rabbitTemplate.setConfirmCallback(confirmCallback);
    }

    /**
     * return机制回调
     */
    private final RabbitTemplate.ReturnsCallback returnsCallback = new RabbitTemplate.ReturnsCallback() {
        /**
         *
         * @param returned 相关信息
         */
        @Override
        public void returnedMessage(ReturnedMessage returned) {
            System.out.println(returned.getMessage());  //消息的相关信息
            System.out.println(new String(returned.getMessage().getBody()));
            System.out.println(returned.getReplyCode());    //错误状态码
            System.out.println(returned.getReplyText());    //错误状态码对应的文本信息
            System.out.println(returned.getExchange()); //交换机的名字
            System.out.println(returned.getRoutingKey());   //路由的key
        }
    };


    public void sendReturn() {
        rabbitTemplate.setReturnsCallback(returnsCallback);
        //错误
        //rabbitTemplate.convertAndSend("exchange_return", "return.km.km", "测试 return 机制");
        //正确
        rabbitTemplate.convertAndSend("exchange_return","return.km","测试 return 机制");
    }
}
